<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Safari HTTPS 连接诊断</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f7;
        }
        .container {
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }
        h1 {
            color: #1d1d1f;
            text-align: center;
            margin-bottom: 30px;
        }
        .test-section {
            margin: 20px 0;
            padding: 20px;
            border: 1px solid #d2d2d7;
            border-radius: 8px;
            background: #fbfbfd;
        }
        .test-section h2 {
            color: #1d1d1f;
            margin-top: 0;
        }
        .status {
            padding: 10px;
            border-radius: 6px;
            margin: 10px 0;
            font-weight: 500;
        }
        .status.success { background: #d1edff; color: #0066cc; }
        .status.error { background: #ffe6e6; color: #d70015; }
        .status.warning { background: #fff4e6; color: #bf5000; }
        .status.info { background: #f0f0f0; color: #333; }
        button {
            background: #007aff;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px 5px;
        }
        button:hover {
            background: #0056b3;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .code {
            background: #f6f6f6;
            padding: 10px;
            border-radius: 4px;
            font-family: 'SF Mono', Monaco, monospace;
            font-size: 14px;
            overflow-x: auto;
        }
        .browser-info {
            background: #e8f4fd;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
        }
        .step {
            margin: 15px 0;
            padding: 15px;
            background: #f9f9f9;
            border-left: 4px solid #007aff;
            border-radius: 0 8px 8px 0;
        }
        .step h3 {
            margin-top: 0;
            color: #007aff;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🧭 Safari HTTPS 连接诊断工具</h1>
        
        <div class="browser-info">
            <h3>🌐 浏览器信息</h3>
            <div id="browser-info"></div>
        </div>

        <div class="test-section">
            <h2>🔍 环境检测</h2>
            <button onclick="detectEnvironment()">检测环境</button>
            <div id="env-results"></div>
        </div>

        <div class="test-section">
            <h2>🔒 证书状态检查</h2>
            <button onclick="checkCertificates()">检查证书</button>
            <div id="cert-results"></div>
        </div>

        <div class="test-section">
            <h2>🌐 网络连接测试</h2>
            <button onclick="testConnections()">测试连接</button>
            <div id="connection-results"></div>
        </div>

        <div class="test-section">
            <h2>💬 API 对话测试</h2>
            <button onclick="testChat()">测试对话</button>
            <div id="chat-results"></div>
        </div>

        <div class="test-section">
            <h2>🛠️ Safari 解决方案</h2>
            <div id="safari-solutions">
                <div class="step">
                    <h3>步骤 1: 信任证书</h3>
                    <p>1. 在Safari中访问 <code>https://localhost:8000</code></p>
                    <p>2. 点击"显示详细信息" → "访问此网站"</p>
                    <p>3. 输入系统密码确认</p>
                </div>
                
                <div class="step">
                    <h3>步骤 2: 系统证书信任</h3>
                    <p>1. 打开"钥匙串访问"应用</p>
                    <p>2. 在"系统"钥匙串中找到localhost证书</p>
                    <p>3. 双击证书 → 展开"信任" → 设置为"始终信任"</p>
                </div>
                
                <div class="step">
                    <h3>步骤 3: 开发者选项</h3>
                    <p>1. Safari → 偏好设置 → 高级</p>
                    <p>2. 勾选"在菜单栏中显示开发菜单"</p>
                    <p>3. 开发 → 停用跨域限制</p>
                </div>
            </div>
        </div>
    </div>

    <script type="module">
        // 显示浏览器信息
        function showBrowserInfo() {
            const info = {
                '用户代理': navigator.userAgent,
                '是否Safari': /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent),
                '是否安全上下文': window.isSecureContext,
                '当前协议': window.location.protocol,
                '当前主机': window.location.hostname,
                '当前端口': window.location.port,
                'WebKit版本': navigator.userAgent.match(/WebKit\/(\d+)/)?.[1] || '未知'
            };

            const browserDiv = document.getElementById('browser-info');
            browserDiv.innerHTML = Object.entries(info)
                .map(([key, value]) => `<strong>${key}:</strong> ${value}`)
                .join('<br>');
        }

        // 检测环境
        window.detectEnvironment = function() {
            const results = document.getElementById('env-results');
            results.innerHTML = '<div class="status info">正在检测环境...</div>';
            
            try {
                const env = {
                    'TLS版本': 'TLS 1.2+',
                    '证书类型': '自签名证书',
                    '证书域名': 'localhost',
                    '前端端口': '8080 (HTTPS)',
                    '后端端口': '8000 (HTTPS)',
                    '混合内容': window.location.protocol === 'https:' ? '无' : '存在'
                };
                
                let html = '<div class="status success">环境检测完成</div>';
                html += Object.entries(env)
                    .map(([key, value]) => `<strong>${key}:</strong> ${value}`)
                    .join('<br>');
                
                results.innerHTML = html;
            } catch (error) {
                results.innerHTML = `<div class="status error">环境检测失败: ${error.message}</div>`;
            }
        };

        // 检查证书状态
        window.checkCertificates = function() {
            const results = document.getElementById('cert-results');
            results.innerHTML = '<div class="status info">正在检查证书...</div>';
            
            const tests = [
                { url: 'https://localhost:8000/health', name: '后端证书' },
                { url: 'https://localhost:8080', name: '前端证书' }
            ];
            
            let html = '';
            let completed = 0;
            
            tests.forEach(test => {
                fetch(test.url, { 
                    method: 'GET',
                    mode: 'cors',
                    credentials: 'omit'
                })
                .then(response => {
                    html += `<div class="status success">${test.name}: ✅ 可访问 (${response.status})</div>`;
                })
                .catch(error => {
                    html += `<div class="status error">${test.name}: ❌ ${error.message}</div>`;
                })
                .finally(() => {
                    completed++;
                    if (completed === tests.length) {
                        results.innerHTML = html;
                    }
                });
            });
        };

        // 测试连接
        window.testConnections = function() {
            const results = document.getElementById('connection-results');
            results.innerHTML = '<div class="status info">正在测试连接...</div>';
            
            const apiBaseUrl = window.location.protocol === 'https:' ? 
                'https://localhost:8000' : 'http://localhost:8000';
            
            // 测试健康检查
            fetch(`${apiBaseUrl}/health`)
                .then(response => response.json())
                .then(data => {
                    results.innerHTML = `
                        <div class="status success">✅ 后端连接成功</div>
                        <div class="code">${JSON.stringify(data, null, 2)}</div>
                    `;
                })
                .catch(error => {
                    results.innerHTML = `
                        <div class="status error">❌ 后端连接失败</div>
                        <div class="status error">错误: ${error.message}</div>
                        <div class="status warning">
                            <strong>可能的原因:</strong><br>
                            • Safari阻止了自签名证书<br>
                            • 需要手动信任证书<br>
                            • 跨域请求被阻止<br>
                            • 混合内容安全策略
                        </div>
                    `;
                });
        };

        // 测试对话
        window.testChat = function() {
            const results = document.getElementById('chat-results');
            results.innerHTML = '<div class="status info">正在测试对话功能...</div>';
            
            const apiBaseUrl = window.location.protocol === 'https:' ? 
                'https://localhost:8000' : 'http://localhost:8000';
            
            const testMessage = {
                message: "你好，这是Safari连接测试",
                conversation_id: "safari_test_" + Date.now()
            };
            
            fetch(`${apiBaseUrl}/api/chat`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(testMessage)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                results.innerHTML = `
                    <div class="status success">✅ 对话功能正常</div>
                    <div class="code">
                        <strong>AI回复:</strong> ${data.reply?.substring(0, 100)}...
                        <br><strong>音频:</strong> ${data.audio_url || '无'}
                        <br><strong>情感:</strong> ${data.emotion || '无'}
                    </div>
                `;
            })
            .catch(error => {
                results.innerHTML = `
                    <div class="status error">❌ 对话功能失败</div>
                    <div class="status error">错误: ${error.message}</div>
                    <div class="status warning">
                        <strong>Safari特有问题:</strong><br>
                        • 自签名证书未被信任<br>
                        • 需要在系统钥匙串中手动信任证书<br>
                        • 可能需要重启Safari
                    </div>
                `;
            });
        };

        // 页面加载时显示浏览器信息
        showBrowserInfo();
    </script>
</body>
</html>